package com.example.test1.controller;


import com.example.test1.bean.UserBean;
import com.example.test1.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
public class UserController {
    @RequestMapping("/users")
    public String showUsers(ModelMap modelMap){
        List<UserBean> userList = userService.getAllUser();
        modelMap.addAttribute("userList",userList);
        return "users";
    }
    public String users(){
        return "users";
    }
    @Resource
    UserService userService;
    @RequestMapping("/user/{id}")
    public String getUserById(@PathVariable("id") int id,ModelMap modelMap){
        UserBean userBean = userService.getUserById(id);
        modelMap.addAttribute("user",userBean);
        return "userInfo";
    }
    @RequestMapping(value = "/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        int nRow = userService.deleteUser(id);
        if (nRow > 0){
            return "redirect:/users";
        }
        return "error";
    }
    @RequestMapping("/addUser")
    @ResponseBody
    public Map addUser(UserBean userBean){

        int flag = userService.insertUser(userBean);
        Map<String, Object> map =new HashMap<String,Object>();
        if (flag ==1){
            map.put("msg","新增用户成功");
            return map;
        }else {
            map.put("msg","新增用户失败");
            return map;
        }
    }
}
